<template>
  <div class="navbar">
    <div class="logo">
      <img src="@/assets/logo/logo_yxb_nowords.png" alt="优学伴家教服务平台">
      <span>优学伴家教服务平台</span>
    </div>
    <div class="nav-menu">
      <div class="nav-item" :class="{ active: currentNav === 'home' }" @click="navigateTo('home')">首页</div>
      <div class="nav-item" :class="{ active: currentNav === 'news' }" @click="navigateTo('news2')">家教资讯</div>
      <div class="nav-item" :class="{ active: currentNav === 'square' }" @click="navigateTo('square')">家教广场</div>

      <div class="nav-item" :class="{ active: currentNav === 'myRequest' }" @click="navigateTo('myRequest')" v-show="roleName=='家长'">我的发布</div>

      <div class="nav-item" :class="{ active: currentNav === 'myOrders' }" @click="navigateTo('myOrders')"
        v-show="roleName=='教员'">我的接单</div>

      <div class="nav-item" :class="{ active: currentNav === 'appointment' }" @click="navigateTo('appointment')">我的预约
      </div>
      
      <div class="nav-item" :class="{ active: currentNav === 'feedback' }" @click="navigateTo('feedback')">留言反馈</div>

      <div class="nav-item" :class="{ active: currentNav === 'feedback/my_words' }" @click="navigateTo('feedback/my_words')">我的留言</div>

      <div class="nav-item" :class="{ active: currentNav === 'application' }" @click="navigateTo('application')" v-show="roleName=='教员'">教员申请</div>
    </div>
    <div class="right-menu">
      <el-dropdown class="avatar-container" trigger="click">
        <div class="avatar-wrapper">
          <span class="user-name">您好，{{ roleName }}{{ userName }}</span>
          <img :src="avatar" class="user-avatar">
          <i class="el-icon-caret-bottom" />
        </div>
        <el-dropdown-menu slot="dropdown">
          <router-link to="/user/profile">
            <el-dropdown-item>个人中心</el-dropdown-item>
          </router-link>
          <router-link to="/feedback/my_words">
            <el-dropdown-item>我的留言</el-dropdown-item>
          </router-link>
          <router-link to="/myOrders">
            <el-dropdown-item v-show="roleName=='教员'">我的接单</el-dropdown-item>
          </router-link>
          <router-link :to="{
            path: '/myRequest',
            query: roleName === '家长' 
              ? { parentName: userName }
              : { teacherName: userName }
          }">
            <el-dropdown-item v-show="roleName=='家长'">我的发布</el-dropdown-item>
          </router-link>
          <router-link :to="{
            path: '/appointment',
            query: roleName === '家长' 
              ? { parentName: userName }
              : { teacherName: userName }
          }">
            <el-dropdown-item>我的预约</el-dropdown-item>
          </router-link>
          <el-dropdown-item divided @click.native="logout">
            <span>退出登录</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'Navbar',
  data() {
    return {
      currentNav: 'home',
      userName: '',
      roleName: ''
    }
  },
  computed: {
    ...mapGetters([
      'avatar',
    ])
  },
  created() {
    this.roleName = localStorage.getItem("roleName")
    this.userName = localStorage.getItem("userName")
    this.updateCurrentNav()

    // 添加事件监听器来检测localStorage的变化
    window.addEventListener('storage', this.handleStorageChange)

    // 监听头像更新事件
    this.$bus.$on('avatarUpdated', this.handleAvatarUpdate)
  },
  beforeDestroy() {
    // 组件销毁前移除事件监听器
    window.removeEventListener('storage', this.handleStorageChange)
    // 移除头像更新事件监听
    this.$bus.$off('avatarUpdated', this.handleAvatarUpdate)
  },
  watch: {
    $route() {
      this.updateCurrentNav()
    }
  },
  methods: {
    // 处理localStorage变化
    handleStorageChange(e) {
      if (e.key === 'userName') {
        this.userName = e.newValue
      }
      if (e.key === 'roleName') {
        this.roleName = e.newValue
      }
    },
    // 处理头像更新
    handleAvatarUpdate(newAvatar) {
      // 更新 Vuex store 中的头像
      this.$store.commit('SET_AVATAR', newAvatar);
      // 强制更新组件
      this.$forceUpdate();
    },
    updateCurrentNav() {
      const path = this.$route.path
      if (path === '/userHome') this.currentNav = 'home'
      else if (path === '/square') this.currentNav = 'square'
      else if (path === '/appointment') this.currentNav = 'appointment'
      else if (path === '/feedback' || path === '/words' ) this.currentNav = 'feedback'

      else if (path === '/feedback/my_words') this.currentNav = 'feedback/my_words'
      
      else if (path === '/news2') this.currentNav = 'news'
      else if (path === '/myOrders') this.currentNav = 'myOrders'
      else if (path === '/application2') this.currentNav = 'application'
      else if (path === '/hone/subject') this.currentNav = 'home'
      else if (path === '/teacherDetail') this.currentNav = 'square'
      else if (path === '/myRequest') this.currentNav = 'myRequest'
    },
    navigateTo(route) {
      this.currentNav = route
      switch (route) {
        case 'home':
          this.$router.push('/userHome')
          break
        case 'news2':
          this.$router.push('/news2')
          break
        case 'square':
          this.$router.push('/square')
          break
        case 'appointment':
          if (this.roleName === "家长") {
            this.$router.push({
              path: '/appointment',
              query: { parentName: this.userName }
            })
          } else {
            this.$router.push({
              path: '/appointment',
              query: { teacherName: this.userName }
            })
          }
          break
        case 'feedback':
          this.$router.push('/words')
          break
        case 'myOrders':
          this.$router.push('/myOrders')
          break
        case 'application':
          this.$router.push('/application2')
          break
        case 'myRequest':
          this.$router.push('/myRequest')
          break
        case 'feedback/my_words':
          this.$router.push('/feedback/my_words')
          break
      }
    },
    async logout() {
      try {
        await this.$confirm('确定退出系统吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        localStorage.removeItem("teacherPhoneNumber")
        localStorage.removeItem("parentPhoneNumber")
        localStorage.removeItem("hasShownNotification")
        localStorage.removeItem("roleName")
        localStorage.removeItem("userId")
        localStorage.removeItem("userName")
        await this.$store.dispatch('LogOut')
        location.href = '/index'
      } catch(err) {
        // 取消退出
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.navbar {
  height: 60px;
  background: linear-gradient(to right, #ce5656, #a90c36);
  display: flex;
  align-items: center;
  padding: 0 20px;
  color: white;

  .logo {
    display: flex;
    align-items: center;
    img {
      height: 40px;
      margin-right: 10px;
    }
    span {
      font-size: 20px;
      font-weight: bold;
    }
  }

  .nav-menu {
    flex: 1;
    margin-left: 50px;
    display: flex;

    .nav-item {
      color: white;
      padding: 0 20px;
      font-size: 16px;
      cursor: pointer;

      &.active {
        font-weight: bold;
      }

      &:hover {
        opacity: 0.8;
      }
    }
  }

  .right-menu {
    .avatar-container {
      .avatar-wrapper {
        display: flex;
        align-items: center;
        .user-avatar {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          margin-right: 8px;
        }
        .user-name {
          color: white;
          margin-right: 5px;
        }
      }
    }
  }
}
</style> 